import React, { useCallback } from 'react';
import { withPropsAPI } from 'gg-editor';
import ForNode from './ForNode';
import ForEdge from './ForEdge';

function DetailForm({ propsAPI, type }) {
  const { getSelected, executeCommand, update, save } = propsAPI;
  const item = getSelected()[0];

  const updateItem = useCallback(
    payload => {
      executeCommand(() => {
        update(item, payload);
      });
    },
    [executeCommand, item, update]
  );

  const getNode = useCallback(
    id => {
      const graph = save();
      const { nodes } = graph;
      return nodes.find(node => node.id === id);
    },
    [save]
  );

  const getInput = useCallback(
    id => {
      const graph = save();
      const { edges = [] } = graph;
      return edges.find(edge => edge.target === id);
    },
    [save]
  );

  if (!item) {
    return null;
  }

  const { model } = item;

  return (
    <>
      {type === 'node' && (
        <ForNode node={model} input={getInput(model.id)} updateNode={updateItem} />
      )}
      {type === 'edge' && (
        <ForEdge edge={model} source={getNode(model.source)} target={getNode(model.target)} />
      )}
    </>
  );
}

export default withPropsAPI(DetailForm);
